package com.zky.gulimall.product.exception;

import com.zky.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author 张开源
 * @Date 2022/9/29 19:39
 * @Version 1.0
 **/
@Slf4j
@RestControllerAdvice(basePackages = "com.zky.gulimall.product.controller")
public class ControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
    log.error("数据校验出现异常:{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();

        Map<String,Object> hashMap=new HashMap<>();
        result.getFieldErrors().forEach(item->{
            String message = item.getDefaultMessage();
            String field = item.getField();
            hashMap.put(field,message);
        });

        return R.error(400,"提交的数据不合法").put("data",hashMap);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Throwable e){
        return R.error();
    }
}
